
/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.web.system.org.controller;

import cc.jweb.adai.web.system.log.service.SysLogService;
import cc.jweb.adai.web.system.org.model.SysUser;
import cc.jweb.adai.web.system.sys.model.SysLog;
import cc.jweb.boot.common.exception.ParameterValidationException;
import cc.jweb.boot.utils.security.PasswordCryptoTool;
import com.jfinal.core.ActionKey;
import com.jfinal.core.NotAction;
import cc.jweb.boot.common.lang.Result;
import cc.jweb.boot.utils.lang.StringUtils;
import cc.jweb.boot.controller.JwebController;
import cc.jweb.boot.db.Db;
import cc.jweb.adai.web.system.generator.utils.GeneratorUtils;
import cc.jweb.boot.security.annotation.Logical;
import cc.jweb.boot.security.annotation.RequiresPermissions;
import io.jboot.web.controller.annotation.RequestMapping;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户
 * 该控制器代码由阿呆代码生成器自动生成
 *
 * @generateDate 2020-12-28 18:45:27
 * @since 1.0
 * @author imlzw
 * @source 阿呆极速开发平台 adai.imlzw.cn
 */
@RequiresPermissions("generator:13:view")
@RequestMapping(value = "/system/org/table2", viewPath = "/WEB-INF/views/cc/jweb/adai/web/system/org/gid_13")
public class Table2SysUserController extends JwebController {

    public void index() {
        render("index.html");
    }
    /**
     * 编辑页面
     */
    @RequiresPermissions("generator:13:edit")
    public void editPage() {
        String id = getPara("user_id");
        SysUser sysUser = null;
        if(id != null) {
            sysUser = SysUser.dao.findById(id);
            if (sysUser == null) {
                sysUser = new SysUser();
            }
        }
        if(sysUser == null) {
            sysUser = new SysUser();
        }
        sysUser.setUserPassword("");
        setAttr("detail", sysUser);
        keepPara();
        render("table2edit.html");
    }

    /**
     * 加载分页列表数据
     */
    @RequiresPermissions("generator:13:list")
    public void list() {
        Map<String, Object> params = getPageParamsPlus();
        params.put("_filters_", GeneratorUtils.parseFilterParams(params));
        Object[] values = getParaValues("values");
        Result result = new Result(false,"未知异常！");
        result.set("code", 400);
        if (StringUtils.isNotBlank(values)){ // formSelects的回显接口
            params.put("_values_",values);
            String valueKey = getPara("valueKey");
            params.put("_valueKey_", valueKey!=null?valueKey:"user_id");
            result.setListData(Db.find(Db.getSqlPara("gid-13-tno-2-cc.jweb.adai.web.system.org.sys_user.queryPageList", params)));
            result.setSuccess(true);
            result.set("code", 0);
        } else {
            result = Db.paginate("gid-13-tno-2-cc.jweb.adai.web.system.org.sys_user.queryPageList", "gid-13-tno-2-cc.jweb.adai.web.system.org.sys_user.count", params);
            result.set("count", result.get(Result.LIST_TOTAL_KEY));
            result.setSuccess(true);
            result.set("code", 0);
        }
        renderJson(result);
    }

    /**
     * 保存用户信息（新增与修改）
     */
    @RequiresPermissions(value = {"generator:13:add","generator:13:edit"}, logical = Logical.OR)
    public void save() {
        SysUser columnModel = getColumnModel(SysUser.class);
        SysUser oldModel = null;
        Object id = columnModel.get("user_id");
        if (id != null) {
            oldModel = SysUser.dao.findById(id);
        }
        // 对密码进行加密
        if (StringUtils.notBlank(columnModel.getUserPassword())) {
            columnModel.setUserPassword(PasswordCryptoTool.encryptPassword(columnModel.getUserPassword()));
        } else {
            if (oldModel != null) {
                columnModel.setUserPassword(oldModel.getUserPassword());
            }
        }
        if (oldModel != null) { // 编辑
            fixModel(columnModel);
            verifyModel(columnModel);
            columnModel.update();
        } else { // 新增

            columnModel.set("create_datetime", new Date());
            fixModel(columnModel);
            verifyModel(columnModel);
            columnModel.save();
        }
        SysLogService.service.setSyslog("组织机构", SysLog.STATUS_SUCCESS ,"保存用户机构信息【" + columnModel.getUserName()+ "】成功！");
        renderJson(new Result(true, "保存用户信息成功！"));
    }

    /**
     *  修正模型数据
     *  避免模型非空字段 无数据时，保存或者更新时异常
     */
    @NotAction
    private void fixModel(SysUser columnModel) {
        Set<String> attrs = columnModel._getAttrsEntrySet().stream().map(stringObjectEntry -> stringObjectEntry.getKey()).collect(Collectors.toSet());
        if(attrs.contains("user_id") && columnModel.get("user_id")==null){
            // 字段默认值为：NULL
            columnModel.remove("user_id");
        }

        if(attrs.contains("user_sex") && columnModel.get("user_sex")==null){
            // 字段默认值为：1
            columnModel.set("user_sex", "1");
        }

    }

    /**
     *  验证数据
     *  对模型中的字段数据进行校验
     */
    @NotAction
    private void verifyModel(SysUser columnModel) {
        Set<String> attrs = columnModel._getAttrsEntrySet().stream().map(stringObjectEntry -> stringObjectEntry.getKey()).collect(Collectors.toSet());
        if(attrs.contains("user_name") && columnModel.getUserName()!=null && columnModel.getUserName().length() > 32){
            throw new ParameterValidationException("用户姓名的长度不能超过32个字符！");
        }
        if(attrs.contains("user_account") && columnModel.getUserAccount()!=null && columnModel.getUserAccount().length() > 32){
            throw new ParameterValidationException("登录账号的长度不能超过32个字符！");
        }
        if(attrs.contains("user_password") && columnModel.getUserPassword()!=null && columnModel.getUserPassword().length() > 128){
            throw new ParameterValidationException("登录密码的长度不能超过128个字符！");
        }
        if(attrs.contains("user_phone") && columnModel.getUserPhone()!=null && columnModel.getUserPhone().length() > 32){
            throw new ParameterValidationException("手机号的长度不能超过32个字符！");
        }
        if(attrs.contains("user_email") && columnModel.getUserEmail()!=null && columnModel.getUserEmail().length() > 128){
            throw new ParameterValidationException("电子邮箱的长度不能超过128个字符！");
        }
    }

    /**
     * 删除记录
     */
    @RequiresPermissions("generator:13:del")
    public void delete() {
        String[] ids = getParaValues("ids");
        if (ids == null || ids.length <= 0) {
            renderJson(new Result(true, "删除成功！"));
            return;
        }
        boolean b = true;
        for(String id : ids) {
            b = b & SysUser.dao.deleteById(id);
         }
        SysLogService.service.setSyslog("组织机构", b ? SysLog.STATUS_SUCCESS : SysLog.STATUS_FAILURE, "删除人员信息【id:" + StringUtils.join(ids, ",") + "】" + (b ? "成功" : "失败") + " !");
        renderJson(new Result(b, b ? "删除成功！" : "删除失败！"));
    }

    // ---- 字段关联接口 ----
    /**
     * org_id 字段关联表列表接口
     */
    @ActionKey("/system/org/table2/org_id/sql/list")
    public void orgIdSqlList() {
        Map<String, Object> params = getPageParamsPlus();
        params.put("_filters_", GeneratorUtils.parseFilterParams(params));
        Object[] values = getParaValues("values");
        Result result = new Result(false,"未知异常！");
        result.set("code", 400);
        if (StringUtils.isNotBlank(values)){ // formSelects的回显接口
            params.put("org_ids",values);
            result.setListData(Db.find(Db.getSqlPara("gid-13-tno-2-cc.jweb.adai.web.system.org.sys_user.org_id_sql_list", params)));
            result.setSuccess(true);
            result.set("code", 0);
        } else {
            result = Db.paginate("gid-13-tno-2-cc.jweb.adai.web.system.org.sys_user.org_id_sql_list", "gid-13-tno-2-cc.jweb.adai.web.system.org.sys_user.org_id_sql_count", params);
            result.set("count", result.get(Result.LIST_TOTAL_KEY));
            result.setSuccess(true);
            result.set("code", 0);
        }
        renderJson(result);
    }

}